package com.cloudptt.api.product.func.call.group;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.cloudptt.api.models.call.RtcpMsg;
import com.cloudptt.api.pjsip.api.SipCallSession;
import com.cloudptt.api.pjsip.api.SipManager;
import com.cloudptt.api.pjsua2.MyCall;
import com.cloudptt.api.product.func.IBroadcast;
import com.cloudptt.api.product.func.call.CallConst;
import com.cloudptt.api.product.func.call.CallFunc;
import com.cloudptt.api.product.func.call.CallTracker;
import com.cloudptt.api.product.log.Log;

public class GroupCallBroadcast extends BroadcastReceiver implements IBroadcast
{
	

	private Context ctx = null;
	private GroupCallTracker callTracker = null;

	public GroupCallBroadcast(Context ctx,GroupCallTracker callTracker)
	{
		this.ctx = ctx;
		this.callTracker = callTracker;

		this.ctx.registerReceiver(this, new IntentFilter(SipManager.ACTION_SIP_CALL_INCOMING));
		this.ctx.registerReceiver(this, new IntentFilter(SipManager.ACTION_SIP_CALL_CHANGED));
		this.ctx.registerReceiver(this, new IntentFilter(SipManager.ACTION_SIP_SPEAKING_CHANGED));
	}


	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		Log.d(GroupCallTracker.THIS_FILE, "Action is " + action);

		if (action.equals(SipManager.ACTION_SIP_CALL_INCOMING)) 
		{
			SipCallSession callSession = intent.getParcelableExtra(SipManager.EXTRA_CALL_INFO);
			Log.d(GroupCallTracker.THIS_FILE, "ACTION_SIP_CALL_INCOMING callInfo is " + callSession);
			callTracker.incomingCall(callSession);
			
		}
		else if (action.equals(SipManager.ACTION_SIP_CALL_CHANGED)) 
		{
			SipCallSession callSession = intent.getParcelableExtra(SipManager.EXTRA_CALL_INFO);
			callTracker.recvCallSession(callSession);
		} 
		else if (action.equals(SipManager.ACTION_SIP_SPEAKING_CHANGED)) 
		{
			String callIdStr = intent.getStringExtra(SipManager.EXTRA_CALL_ID);
			RtcpMsg rtcpMsg = intent.getParcelableExtra(SipManager.EXTRA_SPEAKING_INFO);
			Log.d(GroupCallTracker.THIS_FILE, "onReceive ACTION_SIP_SPEAKING_CHANGED callIdStr = " + callIdStr);
			Log.d(GroupCallTracker.THIS_FILE, "onReceive ACTION_SIP_SPEAKING_CHANGED rtcpMsg is " + rtcpMsg);
			if(rtcpMsg != null)
			{
				callTracker.receiveRtcpMsg(callIdStr,rtcpMsg);
			}
		}
		
	}

	public void clearResource()
	{
		Log.d(GroupCallTracker.THIS_FILE, "GroupCallBroadcast clearResource");
		this.ctx.unregisterReceiver( this );
		this.ctx = null;
		this.callTracker = null;
//		this.curCallSession = null;
	}
}
